#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.

"""NASA MODIS quick viewer."""

__author__ = 'arb@google.com (Anthony Baxter)'

from datetime import datetime
import logging
import os

from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


class MainPage(webapp.RequestHandler):
  """Display a page of NASA MODIS images."""

  def get(self):
    """GET handler."""
    year = self.request.get('year')
    if not year:
      year = datetime.utcnow().strftime('%Y')
    series = self.request.get('series')
    if not series:
      series = datetime.utcnow().strftime('%j')
    prevseries = '%03d' % (int(series) - 1)
    nextseries = '%03d' % (int(series) + 1)
    series = '%03d' % (int(series))
    for img in ('Australia1', 'Australia2', 'Australia3', 'Australia4',
                'Australia5', 'Australia6', 'Tasmania'):
      url = 'http://rapidfire.sci.gsfc.nasa.gov/subsets/?subset=%s.%s%s' %(
          img, year, series)
      logging.info('kicking off %s', url)
      try:
        urlfetch.fetch(url)
      except Exception:
        pass
      date = datetime.strptime('%s %s'%(year, series), '%Y %j'
                              ).strftime('%Y/%m/%d')
    template_values = {
        'date': date,
        'year': year,
        'series': series,
        'nextseries': nextseries,
        'prevseries': prevseries,
        }

    path = os.path.join(os.path.dirname(__file__), 'nasa.html')
    self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication([('/nasa/modis', MainPage)], debug=True)


def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
